<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 服务人员管理
 *
 * @icon fa fa-circle-o
 */
class Worker extends Backend
{

    /**
     * Worker模型对象
     * @var \app\admin\model\deerhome\Worker
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $selectpageFields = 'id,uname,utel';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Worker;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    public function index()
    {
        if (!$this->request->isAjax())
        {
            return $this->view->fetch();
        }
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
                ->with(["shop","lev","card"])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
  
        // foreach($list->items() as &$v){
        //     $v['money_dj']=Db::name("deerhome_order")->where("id",$v['id'])->where("worker_price_to_wallet",0)->where("status",'in',[3,4,5])->SUM("worker_price");
        // }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

   /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $list=db('deerhome_cate')->field('id,name')->where('cate_id',0)->where('status',1)->column('name','id');
            $this->assign("cateData", $list);
            $tagData=db('deerhome_tag')->field('id,name')->column('name','id');
            $this->assign("tagData", $tagData);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['utel']=trim($params['utel']);
        $params['jz_cate_ids']=$this->request->post("jz_cate_ids/a");
        $params['jz_cate_ids']=array_filter($params['jz_cate_ids']);
        if(count($params['jz_cate_ids'])==0){
            $this->error('请选择服务类别');
        }
        $params['jz_cate_ids']='0,'.implode(',',$params['jz_cate_ids']).',0';

        $params['jz_tag_ids']=$this->request->post("jz_tag_ids/a");
        $params['jz_tag_ids']=array_filter($params['jz_tag_ids']);
        if(count($params['jz_tag_ids'])>0){
            $params['jz_tag_ids']='0,'.implode(',',$params['jz_tag_ids']).',0';
        }else{
            $params['jz_tag_ids']='';
        }
     
        $result = false;
        Db::startTrans();
        try {
            $this->model->validateFailException()->validate(
                ['utel' => ['unique'=>'deerhome_worker,utel']],
			    ['utel.unique'=> '手机号已经存在']
            );
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $list=db('deerhome_cate')->field('id,name')->where('cate_id',0)->where('status',1)->column('name','id');
            $this->assign("cateData", $list);
            $tagData=db('deerhome_tag')->field('id,name')->column('name','id');
            $this->assign("tagData", $tagData);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['jz_cate_ids']=$this->request->post("jz_cate_ids/a");
        $params['jz_cate_ids']=array_filter($params['jz_cate_ids']);
        if(count($params['jz_cate_ids'])==0){
            $this->error('请选择服务类别');
        }
        $params['jz_cate_ids']='0,'.implode(',',$params['jz_cate_ids']).',0';

        $params['jz_tag_ids']=$this->request->post("jz_tag_ids/a");
        $params['jz_tag_ids']=array_filter($params['jz_tag_ids']);
        if(count($params['jz_tag_ids'])>0){
            $params['jz_tag_ids']='0,'.implode(',',$params['jz_tag_ids']).',0';
        }else{
            $params['jz_tag_ids']='';
        }
        if(isset($params['utel'])){
            unset($params['utel']);
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $order=Db::name('deerhome_order')->where('worker_id','in',$ids)->find();
        if($order){
            $this->error('该服务人员已经有服务订单，不能删除');
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
